package com.yingxin.yx.framework.security.provider;


import com.yingxin.yx.framework.commons.constant.CommonConst;
import com.yingxin.yx.framework.security.user.PrincipalDto;
import com.yingxin.yx.framework.security.userdetails.AppWexinUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * 自定义登录验证
 */
@Component
public class AppWexinAuthenticationProvider implements AuthenticationProvider {

    @Autowired(required = false)
    private AppWexinUserDetailsService appWexinUserDetailsService;

    @SuppressWarnings("rawtypes")
    @Autowired
    @Qualifier(value = "stringRedisTemplate")
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // openid
        String openid = (String) authentication.getPrincipal();

        // 查询用户是否存在
        PrincipalDto principal = (PrincipalDto) appWexinUserDetailsService.loadUserByUsername(openid);
        if (principal == null) {
            throw new UsernameNotFoundException("用户错误");
        }

        if (CommonConst.TRUE.equals(principal.getFindByIdFlag())) {
            throw new UsernameNotFoundException("用户错误");
        }

        return new UsernamePasswordAuthenticationToken(principal, openid, principal.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }

}